package com.xiaouyudeguang.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Configuration
public class DroolsUtils {

    public static final String RULES_PATH = "rule/";

    public static final String BASE_RULES_PATH = "classpath*:";

    public static KieSession newKieSession(Map<String, String> props) throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] files = resourcePatternResolver.getResources(BASE_RULES_PATH + RULES_PATH + "*.*");
        InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
        KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        for (Resource file : files) {
            String rule = FileUtils.getResource(file.getFile());
		    rule = VelocityUtils.render(rule, file.getFilename(), props);/**/
            knowledgeBuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
        }
        knowledgeBuilder.getErrors().forEach(error -> log.error(error.getMessage()));
        knowledgeBuilder.getKnowledgePackages().forEach(kBase::addPackage);
        return kBase.newKieSession();
    }

    /**
     * 初始化KieBase
     *
     * @param rule
     * @return
     */
    public static KieSession newKieSession(String rule, String logTag, Map<String, String> props) {
        rule = VelocityUtils.render(rule, logTag, props);
        InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
        KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        knowledgeBuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
        knowledgeBuilder.getErrors().forEach(error -> log.error(error.getMessage()));
        knowledgeBuilder.getKnowledgePackages().forEach(kBase::addPackage);
        return kBase.newKieSession();
    }
}
